<div class="row gap-20 masonry pos-r">
	<div class="masonry-sizer col-md-12"></div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900" th:text="#{confServerMail.admin.title}"></h6>
			<div class="mT-30">
				<form id="newConfServerMailForm" th:object="${confServerMailForm}" th:action="@{/saveconfservermail}" method="post">
					<input type='hidden' id="idConfServerMail" th:field="*{idConfServerMail}">
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="issuerMailForm" th:text="#{form.confServerMail.issuer}"></label> 
							<input type="email" class="form-control" id="issuerMailForm" th:field="*{issuerMail}" required>
						</div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-8">
							<label for="hostMailForm" th:text="#{form.confServerMail.host}"></label> 
							<input type="text" class="form-control" id="hostMailForm" th:field="*{hostMail}" required>
						</div>
						<div class="form-group col-md-4">
							<label for="portMailForm" th:text="#{form.confServerMail.port}"></label> 
							<input type="number" class="form-control" id="portMailForm" th:field="*{portMail}" required>
						</div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-6">
							<label for="tslMailForm" th:text="#{form.alarm.tsl}"></label>
							<input type="checkbox" id="tslMailForm" th:field="*{tslMail}" checked>
						</div>
						<div class="form-group col-md-6">
							<label for="authenticationMailForm" th:text="#{form.alarm.authentication}"></label>
							<input type="checkbox" id="authenticationMailForm" th:field="*{authenticationMail}" checked>
						</div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="userMailForm" th:text="#{form.confServerMail.user}"></label> 
							<input type="text" class="form-control" id="userMailForm" th:field="*{userMail}">
						</div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="passwordMailForm" th:text="#{form.confServerMail.password}"></label> 
							<input type="password" class="form-control" id="passwordMailForm" th:field="*{passwordMail}">
						</div>
					</div>
					
					<button id="saveBtn" type="submit" class="btn btn-primary" 
						th:utext="#{button.save}">
					</button>
					
					<button id="cleanBtn" class="btn btn-primary" 
						onclick="cleanForm('#newConfServerMailForm');"
						th:utext="#{button.cleanForm}">
					</button>
					
				</form>
			</div>
		</div>
	</div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900" th:text="#{mail.admin.title}"></h6>
			<div class="mT-30">
				<form id="mailForm" th:object="${mailform}" th:action="@{/saveMail}"
					method="post">
					<input type='hidden' class='primarykey' id="idMail"
						th:field="*{idMail}">
					<div class="form-row">
						<div class="form-group col-md-12"><label for="emailAddress"
							th:text="#{form.mail.emailAddress}"></label> <input type="email"
							class="form-control" id="emailAddress" th:field="*{emailAddress}"
							required></div>
					</div>
					<button id="mailBtn" type="submit" class="btn btn-primary" th:text="#{button.save}"></button>
					<button id="cleanBtn" class="btn btn-primary" onclick="cleanForm('#mailForm');" th:text="#{button.cleanForm}"></button>
				</form>
			</div>
		</div>
		<div class="bgc-white bd bdrs-3 p-20 mB-20">
			<h6 class="c-grey-900 mB-20" th:text="#{table.mail.title}"></h6>
			<table id="mailTable" class="table table-striped table-bordered"
				cellspacing="0" width="100%">
				<thead>
					<tr>
						<th></th>
						<th th:text="#{table.mail.emailAddress}"></th>
					</tr>
				</thead>
			</table>
		</div>
	</div>
</div>

<script th:inline="javascript">

$(document).ready(function() {
	
	// Gestión de las datatables
	var actionSaveMail = /*[[@{/savemail}]]*/;
	var actionEmails = /*[[@{/emails}]]*/;
	var actionDeleteMail = /*[[@{/deletemail}]]*/;
	var getMails = /*[[@{/mailsdatatable}]]*/;
	var tblMail = $('#mailTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    
	    altEditor: true,
	    buttons: [{extend: 'selected',text: 'Editar',name: 'editPageForm',
	    	action: function ( e, dt, node, config ) {
				// Para el action 'Editar' obtenemos los valores de la fila seleccioanda
				// directamente y los copiamos al formulario
				for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
	                id: o.context[0].aoColumns[e].mData,
	            	title: o.context[0].aoColumns[e].sTitle                
	            });
				var d = dt.rows({
                    selected: !0
                })
                
                var idMail = d.data()[0][a[0].id]
				var emailAddress = d.data()[0][a[1].id]
				
                $("#idMail").val(idMail);
                $("#emailAddress").val(emailAddress);
			}
	    }, {extend: 'selected',text: 'Eliminar',name: 'delete'}],
	
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getMails,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "mailForm";
	        }
	      },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idMail",
	          "visible": false},
	        { "data": "emailAddress" }
		          
	        ]
		}).on('crudaction', function(e, accion, idMail, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'delete':
		        	var type = $('form[name="altEditor-form"] input').attr('id');
		        	if (type == 'idMail'){
		        		$.ajax(actionDeleteMail,{
			            	data:$.param({'id':idMail, 'index':rowindex}),
			                type:'POST',
			                success: function(data){
			                    
			                	if (data == "-1" && $('#errorModalMail').length == 0){
			                		$('#mailForm').append('<div id="errorModalMail" class="alert alert-danger" role="alert"><strong>' + [[#{mail.admin.error.inUse}]] + '</strong></div>');
			                	}else{
									$('#errorModalMail').remove();
								}
			                	
			                	// Se oculta la capa 'cargando...'
			                	hide();
			                    tblMail.row(data.index).remove().draw();
			                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                },
			                error:function(){}
			            });
		        	}else{
						// Se oculta la capa 'cargando...'
						hide();
					}
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
	
	// Control del botón para guardar un correo
	$( "#mailBtn" ).click(function( event ) {
	  event.preventDefault();

	  var formData = JSON.stringify($("#mailForm").serializeJSON());
	  var url = /*[[@{/savemail}]]*/;
	  
	  loading();
	  if ($('#mailForm')[0].checkValidity() === false) {
		  hide();
		  
		  $('#mailForm *').filter(':input').each(function(){
      	    
          	if(!$(this)[0].checkValidity()){
      	  	 	$("#" + $(this).attr('id')).addClass("has-error");
      	    } else {
      	  	 	$("#" + $(this).attr('id')).removeClass("has-error");
      	    }
      	    
      	  });
		  
	  } else{
		  $.ajax({
			  type: "POST",
			  url: url,
			  data: formData,
			  success: function(data){
				  
				  var errores = JSON.parse(data.error);
				  
				  if (data.error != null){
					  jQuery.each(errores, function(i, val) {
					  	$('#alarmForm *').filter('span').each(function(){
							if (i == $(this).attr('id')){
								$("#" + i).text(val);
							}
						});
					  });
				  }else{
					  $("#mailForm")[0].reset();
					  $('#mailForm *').filter('span').each(function(){
							$(this).text('');
						});
				  }
				  
				  hide();
				  tblMail.row.add($(data.data)).draw(false);
				  
				  $('#mailForm *').filter(':input').each(function(){
					  $("#" + $(this).attr('id')).removeClass("has-error");
				  });
				  
				  if ($('#errorModalMail').length > 0){
					  $('#errorModalMail').remove();
				  }
				  
			  },
			  error:function(){
				  hide();
				  $('#mailForm').append('<div id="errorModalMail" class="alert alert-danger" role="alert"><strong>' + [[#{mail.admin.error.sameName}]] + '</strong></div>');
			  },
			  dataType: "json",
			  contentType : "application/json"
			});
	  }
	});
		
});

$( "#saveBtn" ).click(function( event ) {
	  event.preventDefault();
	  
	  var formData = JSON.stringify($("#newConfServerMailForm").serializeJSON());
	  var url = /*[[@{/saveconfservermail}]]*/ null;
	  
	  loading();
	  if ($('#newConfServerMailForm')[0].checkValidity() === false) {
		  hide();
		  
		  $('#newConfServerMailForm *').filter(':input').each(function(){
  	    
	          if(!$(this)[0].checkValidity()){
	      	   	$("#" + $(this).attr('id')).addClass("has-error");
	      	  } else {
	      	   	$("#" + $(this).attr('id')).removeClass("has-error");
	      	  }
  	    
  	  });
		  
	  } else{
		  $.ajax({
			  type: "POST",
			  url: url,
			  data: formData,
			  dataType: "json",
			  contentType : "application/json",
			  success: function(data, error){
				  hide();
				  
				  $('#idConfServerMail').val(data.idConfServerMail);
				  $('#issuerMailForm').val(data.issuerMail);
				  $('#hostMailForm').val(data.hostMail);
				  $('#portMailForm').val(data.portMail);
				  $('#tslMailForm').val(data.tslMail);
				  $('#authenticationMailForm').val(data.authenticationMail);
				  $('#userMailForm').val(data.userMail);
				  $('#passwordMailForm').val(data.passwordMail);
				  
				  $('#newConfServerMailForm *').filter(':input').each(function(){
					 $("#" + $(this).attr('id')).removeClass("has-error");
				  });
				   
				  if ($('#errorModalConfMail').length > 0){
					 $('#errorModalConfMail').remove();
				  }
				  
			  },
			  error:function(){
				  hide();
				  if ($('#errorModalConfMail').length > 0){
						 $('#errorModalConfMail').remove();
					  }
				  $('#newConfServerMailForm').append('<div id="errorModalConfMail" class="alert alert-danger" role="alert"><strong>' + [[#{mail.admin.error.saveConfMail}]] + '</strong></div>');
			  }
			});
	  }

});

function cleanForm(f){
	$(f + ' *').filter(':input').each(function(){
		$(this).val('');
	});
	$(f + ' *').filter('span').each(function(){
		$(this).text('');
	});
	$(f + " select").select2().val('').change();
	$(f).find(".alert").remove();
}

</script>